package org.ezplatform.office.rd.common;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;


public class HtmlToPdf {
    private static Logger logger = Logger.getLogger(HtmlToPdf.class.getName());

    // 安全的路径验证模式
    private static final Pattern SAFE_PATH_PATTERN = Pattern.compile("^[a-zA-Z0-9._/\\\\-]+$");
    private static final Pattern DANGEROUS_CHARS = Pattern.compile("[;&|`$<>\"'\\n\\r]");

//    private static final String TOPDFTOOL = "D:/jboss/wkhtmltopdf/bin/wkhtmltopdf";

    /**
     * html转pdf
     * @param srcPath html路径，可以是硬盘上的路径，也可以是网络路径
     * @param destPath pdf保存路径
     * @return 转换成功返回true
     */
    public boolean convert(String srcPath, String destPath,String toolPath) {
        System.out.println("============html转PDF开始=============");
        System.out.println("============srcPath============="+srcPath);
        System.out.println("============destPath============="+destPath);

        // 输入验证和安全检查
        if (!isValidPath(srcPath) || !isValidPath(destPath) || !isValidPath(toolPath)) {
            logger.error("Invalid path parameters detected. Possible command injection attempt.");
            return false;
        }

        // 检查工具路径是否存在且为可执行文件
        File toolFile = new File(toolPath);
        if (!toolFile.exists() || !toolFile.canExecute()) {
            logger.error("Tool path does not exist or is not executable: " + toolPath);
            return false;
        }

        File file = new File(destPath);
        File parent = file.getParentFile();
        // 如果pdf保存路径不存在，则创建路径
        if (!parent.exists()) {
            parent.mkdirs();
        }

        // 使用ProcessBuilder构建安全的命令
        List<String> command = Arrays.asList(
                toolPath,
                "--page-size", "A4",
                srcPath,
                destPath
        );

        boolean result = true;
        try {
            ProcessBuilder pb = new ProcessBuilder(command);
            pb.redirectErrorStream(true);
            Process proc = pb.start();
            HtmlToPdfInter error = new HtmlToPdfInter(
                    proc.getErrorStream());
            HtmlToPdfInter output = new HtmlToPdfInter(
                    proc.getInputStream());
            error.start();
            output.start();
            proc.waitFor();
            System.out.println("HTML2PDF成功，参数---html路径：{},pdf保存路径 ：{}");
        } catch (Exception e) {
            System.out.println("HTML2PDF失败，srcPath地址：{},错误信息：{}");
            logger.error("HTML2PDF conversion failed", e);
            result = false;
        }
        System.out.println("============html转PDF结束=============");
        return result;
    }

    /**
     * 验证路径参数的安全性
     * @param path 要验证的路径
     * @return 如果路径安全返回true，否则返回false
     */
    private boolean isValidPath(String path) {
        if (path == null || path.trim().isEmpty()) {
            return false;
        }

        // 检查是否包含危险字符
        if (DANGEROUS_CHARS.matcher(path).find()) {
            return false;
        }

        // 检查路径遍历攻击
        if (path.contains("..") || path.contains("//")) {
            return false;
        }

        // 基本的路径格式验证
        return SAFE_PATH_PATTERN.matcher(path).matches();
    }
}
